from dto.strategy_assessment import RiskAssessment
from dto.strategy_calculate_result import StrategyCalculateResult
from service.das.stock_assessment_das import RiskAssessmentService
from service.das.stock_assessment_item_das import (
    AntRiskAssessmentItem,
    RiskAssessmentItemService,
)
from service.das.stock_monitor_das import AntMonitorStock


class StrategyViewQueryService:

def searchFinalResult(self, stockInfo: AntMonitorStock) -> StrategyCalculateResult:
    """
    聚合查询，返回 StrategyCalculateResult 对象
    :param stockInfo: 股票信息对象 (AntMonitorStock)
    :return: 聚合的 StrategyCalculateResult
    """
    try:
        riskService = RiskAssessmentService()
        riskItemService = RiskAssessmentItemService()
        stock_code = stockInfo.stock_code

        # 查询 AntRiskAssessmentModel 的股票信息
        stock_record = riskService.get_risk_assessment_by_code(stock_code)

        # 查询 AntRiskAssessmentItem 的风险明细
        risk_items = riskItemService.query_risk_assessment_items_by_code(stock_code)

        # 创建 StrategyCalculateResult 对象
        result = StrategyCalculateResult(
            stock_info=stockInfo,
            latest_price=stockInfo.monitor_current_price,
            total_score=0,
            risk_level=0,
            focus_level=0,
        )

        # 设置主数据的总得分、风险等级和关注等级
        if stock_record:
            result.total_score = stock_record.final_point or 0
            result.risk_level = stock_record.risk_level or 1
            result.focus_level = stockInfo.stock_focus_level or 1

        # 转换风险明细为 RiskAssessment 对象并添加到结果中
        for item in risk_items:
            risk_assessment = RiskAssessment(
                stock_code=item.stock_code,
                description=item.description or "",
                config=StrategyInfoMetadata(
                    strategy_code=item.strategy_code,
                    strategy_name=item.strategy_name,
                    strategy_group=item.strategy_group or 0,
                    strategy_type=item.strategy_type or "",
                    analysis_day=item.analysis_day or 0,
                    strategy_level=item.strategy_level or 1,
                ),
                node_point=item.node_point or 0,
            )
            result.risk_assessments.append(risk_assessment)

        # 聚合所有风险明细的节点得分，计算总得分
        result.total_score += sum(
            assessment.node_point for assessment in result.risk_assessments
        )

        return result

    except Exception as e:
        print(f"查询时出错: {e}")
        return StrategyCalculateResult()
